import {defineStore} from 'pinia'
import {ref} from 'vue'

export const useAppStore = defineStore('app', () => {
  // 侧边栏状态
  const sidebarCollapsed = ref(false)
  
  // 设备类型
  const device = ref('desktop') // desktop, tablet, mobile
  
  // 主题
  const theme = ref('light') // light, dark
  
  // 加载状态
  const globalLoading = ref(false)
  
  // 搜索历史
  const searchHistory = ref(JSON.parse(localStorage.getItem('searchHistory') || '[]'))
  
  // 切换侧边栏
  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
  }
  
  // 设置设备类型
  const setDevice = (deviceType) => {
    device.value = deviceType
  }
  
  // 切换主题
  const toggleTheme = () => {
    theme.value = theme.value === 'light' ? 'dark' : 'light'
  }
  
  // 设置全局加载状态
  const setGlobalLoading = (loading) => {
    globalLoading.value = loading
  }
  
  // 添加搜索历史
  const addSearchHistory = (keyword) => {
    if (!keyword.trim()) return
    
    // 移除重复项
    const index = searchHistory.value.indexOf(keyword)
    if (index > -1) {
      searchHistory.value.splice(index, 1)
    }
    
    // 添加到开头
    searchHistory.value.unshift(keyword)
    
    // 限制数量
    if (searchHistory.value.length > 10) {
      searchHistory.value = searchHistory.value.slice(0, 10)
    }
    
    // 保存到本地存储
    localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
  }
  
  // 清除搜索历史
  const clearSearchHistory = () => {
    searchHistory.value = []
    localStorage.removeItem('searchHistory')
  }
  
  // 移除单个搜索历史
  const removeSearchHistory = (keyword) => {
    const index = searchHistory.value.indexOf(keyword)
    if (index > -1) {
      searchHistory.value.splice(index, 1)
      localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
    }
  }

  return {
    // 状态
    sidebarCollapsed,
    device,
    theme,
    globalLoading,
    searchHistory,
    
    // 方法
    toggleSidebar,
    setDevice,
    toggleTheme,
    setGlobalLoading,
    addSearchHistory,
    clearSearchHistory,
    removeSearchHistory
  }
})
